package org.brownflat.lighthouse.web.init;

import org.apache.log4j.Logger;
import org.brownflat.lighthouse.monitoring.monitor.MonitoringService;
import org.quartz.impl.StdScheduler;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

public class InitServlet extends HttpServlet {
    private static final Logger LOG = Logger.getLogger(InitServlet.class);

    public void init() throws ServletException {
        super.init();
        getServletContext().setAttribute("version", getVersion());
        getServletContext().setAttribute("started", new Date().toString());
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        StdScheduler scheduler = (StdScheduler) wac.getBean("scheduler");
        MonitoringService monitoringService = (MonitoringService) wac.getBean("monitoringService");

        try {
            LOG.info("Starting Scheduler...");
            scheduler.start();
            monitoringService.start();
            LOG.info("Lighthouse loaded.");
        } catch (Exception e) {
            LOG.fatal(e);
        }
    }

    private String getVersion() {
        try {
            InputStream inputStream = getServletContext().getResourceAsStream("/META-INF/maven/org.brownflat/lighthouse/pom.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            return (String) properties.get("version");
        } catch (Throwable th) {
            return "UNKNOWN VERSION";
        }
    }
}
